package com.example.springbootshiro.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.springbootshiro.entity.JsonResult;
import com.example.springbootshiro.entity.OfficeContent;
import com.example.springbootshiro.service.OfficeContentService;

import org.apache.poi.common.usermodel.fonts.FontGroup;
import org.apache.poi.hslf.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.Color;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/office")
public class OfficeController {

    @Autowired
    private OfficeContentService officeContentService;

    @Value("${image_service}")
    private String imageService;

    @Value("${image_path}")
    private String imagePath;

    private static final String FONT_FAMILY = "宋体";

    private static final String PPTX_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
    private static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition";
    private static final String HEADER_ATTACHMENT = "attachment; filename=example.pptx";



    @RequestMapping("/pdfTest")
    @ResponseBody
    public JsonResult pdfTest(){
        JsonResult jsonResult = new JsonResult();
        return jsonResult;
    }

    @RequestMapping("/ppt")
    public String ppt(Model model){
        model.addAttribute("imageService",imageService);
        return "/office/ppt";
    }

    @RequestMapping("/excel")
    public String excel(Model model){
        model.addAttribute("imageService",imageService);
        return "/office/excel";
    }

    @RequestMapping("/ppt-list")
    public String list(Model model){
        model.addAttribute("imageService",imageService);
        return "";
    }

    @RequestMapping("/listData")
    @ResponseBody
    public JsonResult listData(Integer page, Integer size, String param){
        JsonResult jsonResult = new JsonResult();
        IPage<OfficeContent> iPage = officeContentService.pageOfficeContent(page, size, param);
        jsonResult.setData(iPage);
        jsonResult.setSuccess(true);
        jsonResult.setMsg("ok");
        return jsonResult;
    }

    @RequestMapping("/info")
    public String info(){
        return "/office/info";
    }

    @RequestMapping("/listAll")
    @ResponseBody
    public JsonResult listAll(String param,String param2, String param3){
        JsonResult jsonResult = new JsonResult();
        List<OfficeContent> officeContents = officeContentService.selectAll(param, param2, param3);
        jsonResult.setData(officeContents);
        jsonResult.setSuccess(true);
        jsonResult.setMsg("ok");
        return jsonResult;
    }

    /*private boolean matchString(String param){
        String regex = "^(?=.*\\+.*\\+)(?=.*\\.).*$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(param);
        return  matcher.matches();
    }*/

    @RequestMapping("/pptUpload")
    @ResponseBody
    public JsonResult pptUpLoad(@RequestParam("file") MultipartFile file,@RequestParam("param")String param){
        JsonResult jsonResult = new JsonResult();
       /* if (!matchString(file.getOriginalFilename())){
            jsonResult.setMsg("文件格式错误!");
            jsonResult.setSuccess(true);
            return jsonResult;
        }*/
        String filePath = "";
        try {
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = getFormatter("yyyy-MM-dd");
            //图片存放路径
            String dateString = imagePath + currentDate.format(formatter) +"/";
            //图片保存路径
            String dateFile = "/"+currentDate.format(formatter) +"/";
            Path path = Paths.get(dateString);
            if (Files.notExists(path)){
                Files.createDirectories(path);
            }
            byte[] bytes = file.getBytes();
            String[] originalFilename = file.getOriginalFilename().split("\\+");
            String availableTime = originalFilename[0];
            String supplierName = originalFilename[1];
            String fileName = originalFilename[2];

            filePath = dateString + fileName;
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
            stream.write(bytes);
            stream.close();
            List<OfficeContent> officeContents = PPTtoImage(filePath, fileName,availableTime,supplierName, param, dateString,dateFile);
            List<OfficeContent> add = officeContentService.add(officeContents);
            if (!add.isEmpty()){
                jsonResult.setData(add);
                jsonResult.setMsg("ok");
                jsonResult.setSuccess(true);
            }else {
                jsonResult.setMsg("error");
                jsonResult.setSuccess(false);
            }

        }catch (Exception e){
            jsonResult.setMsg("上传失败！");
            jsonResult.setSuccess(false);
        }finally {
            // 删除PPT文件
            File pptFile = new File(filePath);
            if (pptFile.exists()) {
                pptFile.delete();
            }
        }
        return jsonResult;
    }




    private static List<OfficeContent> PPTtoImage(String file, String fileName, String availableTime, String supplier,
                                                  String param, String dateString,String dateFile) throws FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream(file);
        try {
            if (fileName.endsWith(".pptx") || fileName.endsWith(".PPTX")) {
                return pptx2Image(fileInputStream,fileName,availableTime, supplier, param,dateString,dateFile);
            } else {
                return ppt2Image(fileInputStream,fileName,availableTime, supplier,param, dateString,dateFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将pptx转成图片
     */
    private static List<OfficeContent> pptx2Image(FileInputStream fileInputStream, String fileName,String availableTime, String supplier,
                                                  String param,String dateString,String dateFile) throws Exception {
        List<OfficeContent> list = new ArrayList<>();
        // 获取系统可用字体
//        FileInputStream is = new FileInputStream(filePath + fileName);
        XMLSlideShow ppt = new XMLSlideShow(fileInputStream);
        Dimension pgSize = ppt.getPageSize();
        int pageSize = ppt.getSlides().size();
        //System.out.println("ppt 总页数：{}， 尺寸: width={},height={}"+ pageSize + pgSize.width + pgSize.height);
        List<String> imgFiles = new ArrayList<>();

        for (int i = 0; i < pageSize; i++) {
            String contentText = "";

            String imagePath ="";

            String name = "";

            //防止中文乱码
            handlerPPTXEncoding(ppt, i);
            //获取备注
            XSLFSlide xslfShapes = ppt.getSlides().get(i);
            XSLFNotes notesSlide = ppt.getNotesSlide(xslfShapes);
            List<List<XSLFTextParagraph>> textParagraphs = notesSlide.getTextParagraphs();
            String makers = "";
            for (List<XSLFTextParagraph> text1 :textParagraphs){
                for (XSLFTextParagraph text2: text1){
                    makers += text2.getText();
                }
            }
            String price = "";
            if (makers.indexOf("搜索价") != -1){
                if (makers.indexOf(":") != -1){
                    price = makers.split(":")[1];
                }
                if (makers.indexOf("：") != -1){
                    price = makers.split("：")[1];
                }
            }
            System.out.println(price);

            List<XSLFShape> shapes = ppt.getSlides().get(i).getShapes();
            for (XSLFShape shape : shapes) {
                if (shape instanceof XSLFTextShape) {
                    XSLFTextShape tsh = (XSLFTextShape) shape;
                    for (XSLFTextParagraph p : tsh) {
                        for (XSLFTextRun r : p) {
                            contentText += r.getRawText() +"";
                        }
                    }
                }
                /*if (shape instanceof XSLFPictureShape) {
                    // 这是一个图片形状
                    XSLFPictureShape pictureShape = (XSLFPictureShape) shape;
                    byte[] data = pictureShape.getPictureData().getData();
                    ByteArrayInputStream bis = new ByteArrayInputStream(data);
                    BufferedImage image = ImageIO.read(bis);
                    BufferedImage compressedImage = compressImage(image,800,600,200);
                    String date_ = generateUniqueCode();
                    ImageIO.write(compressedImage, "JPG", new File(dateString+date_+".jpg"));
                    imagePath += dateFile+date_+".jpg;";

                }*/
            }

            if ("".equals(imagePath)){

                BufferedImage img = new BufferedImage(pgSize.width, pgSize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                // clear the drawing area
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgSize.width, pgSize.height));
                // render
                ppt.getSlides().get(i).draw(graphics);
                // save the output
                String pptName = fileName.substring(0, fileName.lastIndexOf("."));
                // String newImgPath = "/home/digitalData/imgPPT/"+pptName+"/";
                //String newImgPath = "D:\\home\\wwwroot\\static\\images\\";
                //File imgPath = new File(newImgPath);
                //if (imgPath.exists()) {//图片目录存在则删除
                    //imgPath.delete();
               // }
                //imgPath.mkdirs();
                String date_ = generateUniqueCode();
                String file = dateString + date_ + ".png";
                imgFiles.add(file);
                FileOutputStream out = new FileOutputStream(file);
                javax.imageio.ImageIO.write(img, "png", out);
                IOUtils.closeQuietly(out);
                imagePath += dateFile + date_ + ".png;";
            }
            OfficeContent content = new OfficeContent();
            content.setContent(contentText);
            content.setImages(imagePath);
            content.setFileName(fileName);
            content.setRemark(param);
            String createTime = getCreateTime();
            content.setCreateTime(createTime);
            content.setAvailableTime(availableTime);
            content.setSupplierName(supplier);
            list.add(content);
        }
        IOUtils.closeQuietly(fileInputStream);
        return list;
    }

    /**
     * 将ppt转成图片,保存在同一目录的image目录下
     *
     * @param fileName ppt 文件名
     */
    private static List<OfficeContent> ppt2Image(FileInputStream fileInputStream, String fileName,String availableTime, String supplier,
                                                 String param, String dateString,String dateFile) throws IOException {
        List<OfficeContent> list = new ArrayList<>();
        // 获取系统可用字体
        HSLFSlideShow ppt = new HSLFSlideShow(fileInputStream);
        Dimension pgSize = ppt.getPageSize();
        List<String> imgFiles = new ArrayList<>();
        for (int i = 0; i < ppt.getSlides().size(); i++) {
            String contentText = "";
            String imagePath ="";
            String name = "";
            handlerPPTEncoding(ppt, i);
            //获取备注
            HSLFNotes hslfShapes = ppt.getNotes().get(i);
            List<List<HSLFTextParagraph>> textParagraphs = hslfShapes.getTextParagraphs();
            String makers = "";
            for (List<HSLFTextParagraph> text1 :textParagraphs){
                for (HSLFTextParagraph text2: text1){
                    makers += text2;
                }
            }
            String price = "";
            if (makers.indexOf("搜索价") != -1){
                if (makers.indexOf(":") != -1){
                    price = makers.split(":")[1];
                }
                if (makers.indexOf("：") != -1){
                    price = makers.split("：")[1];
                }
            }
            System.out.println(price);

            for (HSLFShape shape : ppt.getSlides().get(i).getShapes()) {
                if (shape instanceof HSLFTextShape) {
                    HSLFTextShape tsh = (HSLFTextShape) shape;
                    for (HSLFTextParagraph p : tsh) {
                        contentText += p + "";
                    }
                }
                /*if (shape instanceof HSLFPictureShape) {
                    HSLFPictureShape pictureShape = (HSLFPictureShape) shape;
                    byte[] data = pictureShape.getPictureData().getData();
                    ByteArrayInputStream bis = new ByteArrayInputStream(data);
                    BufferedImage image = ImageIO.read(bis);
                    BufferedImage compressedImage = compressImage(image,800,600,200);
                    String date_ = generateUniqueCode();
                    ImageIO.write(compressedImage, "JPG", new File(dateString +date_+".jpg"));
                    imagePath+= dateFile+date_+".jpg;";
                }*/

            }
            if ("".equals(imagePath)){
                // 防止中文乱码

                BufferedImage img = new BufferedImage(pgSize.width, pgSize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                // clear the drawing area
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgSize.width, pgSize.height));
                // render
                ppt.getSlides().get(i).draw(graphics);
                // save the output
                String pptName = fileName.substring(0, fileName.lastIndexOf("."));
                //String newImgPath = "/home/digitalData/imgP/"+pptName+"/";
                //File imgPath = new File("D:\\home\\wwwroot\\static\\images\\");
                /*if (imgPath.exists()) {
                    imgPath.delete();
                }*/
                //imgPath.mkdirs();
                String date_ = generateUniqueCode();
                String file = dateString+date_+".png";
                imgFiles.add(file);
                FileOutputStream out = new FileOutputStream(file);
                javax.imageio.ImageIO.write(img, "png", out);
                IOUtils.closeQuietly(out);
                imagePath+= dateFile+date_+".png;";

            }
            OfficeContent content = new OfficeContent();
            content.setContent(contentText);
            content.setImages(imagePath);
            content.setFileName(fileName);
            content.setRemark(param);
            String createTime = getCreateTime();
            content.setCreateTime(createTime);
            content.setAvailableTime(availableTime);
            content.setSupplierName(supplier);
            list.add(content);
        }
        IOUtils.closeQuietly(fileInputStream);
        return list;
    }


    private static void handlerPPTEncoding(HSLFSlideShow ppt, int index) {
        for (HSLFShape shape : ppt.getSlides().get(index).getShapes()) {
            if (shape instanceof HSLFTextShape) {
                HSLFTextShape tsh = (HSLFTextShape) shape;
                for (HSLFTextParagraph p : tsh) {
                    for (HSLFTextRun r : p) {
                        String fontFamily = "宋体";
                        //r.setFontFamily(fontFamily);
                        r.setFontFamily("宋体", FontGroup.EAST_ASIAN);
                        r.setFontFamily("宋体", FontGroup.LATIN);
                    }
                }
            }
        }
    }

    private static void handlerPPTXEncoding(XMLSlideShow ppt, int index) {
        for (XSLFShape shape : ppt.getSlides().get(index).getShapes()) {
            if (shape instanceof XSLFTextShape) {
                XSLFTextShape tsh = (XSLFTextShape) shape;
                for (XSLFTextParagraph p : tsh) {
                    for (XSLFTextRun r : p) {
                        //String fontFamily = r.getFontFamily();
                        String fontFamily = "宋体";
                        //r.setFontFamily(fontFamily);
                        r.setFontFamily("宋体", FontGroup.EAST_ASIAN);
                        r.setFontFamily("宋体", FontGroup.LATIN);
                    }
                }
            }
        }
    }





    /*@RequestMapping("/pptUpload")
    @ResponseBody
    public JsonResult pptUpload(@RequestParam("file") MultipartFile file,@RequestParam("param")String param){
        JsonResult jsonResult = new JsonResult();
        String filePath = "";
        try {
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = getFormatter("yyyy-MM-dd");
            String dateString = imagePath + currentDate.format(formatter) +"/";
            String dateFile = "/"+currentDate.format(formatter) +"/";
            Path path = Paths.get(dateString);
            try {
                if (Files.notExists(path)) {
                    Files.createDirectories(path);
                } else {
                    System.out.println("文件夹已存在: " + dateString);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            byte[] bytes = file.getBytes();
            // 定义文件保存路径，可以根据需要修改
            String fileName = file.getOriginalFilename();
            filePath = dateString + fileName;
            // 将文件保存到服务器
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
            stream.write(bytes);
            stream.close();
            Presentation ppt = new Presentation();
            ppt.loadFromFile(filePath);
            //读取文字
            String lineSeparator = System.getProperty("line.separator");
            List<OfficeContent> list = new ArrayList<>();
            //遍历文档中的幻灯片，提取文本、图片
            for (Object slide : ppt.getSlides()) {

                //文字
                String buffer = "";
                String images ="";
                String name = "";

                for (Object shape : ((ISlide) slide).getShapes()) {
                    if (shape instanceof IAutoShape) {
                        for (Object tp : ((IAutoShape) shape).getTextFrame().getParagraphs()) {
                            *//*if (((ParagraphEx) tp).getText().indexOf("品名") != -1){
                                name = ((ParagraphEx) tp).getText().split(":")[1];
                            }*//*
                            if (!"".equals( ((ParagraphEx) tp).getText())){
                                buffer += ((ParagraphEx) tp).getText()+"<br>";
                            }

                        }
                    }
                }
                boolean imageType = true;

                for(int i = 0; i< ((ISlide)slide).getShapes().getCount(); i++) {
                    IShape shape = ((ISlide)slide).getShapes().get(i);
                    String date_ = generateUniqueCode();
                    String imagePath = String.format(dateString+date_+"-%1$s.jpg", i);
                    if (shape instanceof SlidePicture || shape instanceof PictureShape){
                        if(shape instanceof SlidePicture) {
                            images += String.format(dateFile + date_+"-%1$s.jpg",i) + ";";
                            SlidePicture pic = (SlidePicture) shape;
                            BufferedImage image = pic.getPictureFill().getPicture().getEmbedImage().getImage();
                            BufferedImage compressedImage = compressImage(image,800,600,200);
                            ImageIO.write(compressedImage, "JPG", new File(imagePath));
                        }
                        if(shape instanceof PictureShape) {
                            images += String.format(dateFile + date_+"-%1$s.jpg",i) + ";";
                            PictureShape ps = (PictureShape) shape;
                            BufferedImage image = ps.getEmbedImage().getImage();
                            ImageIO.write(image, "JPG", new File(imagePath));
                        }
                    }

                    if (shape.getFill().getFillType() == FillFormatType.PICTURE && imageType){
                        images += String.format(dateFile + date_+"-%1$s.jpg",i) + ";";

                        BufferedImage image = ((ISlide) slide).saveAsImage();
                        ImageIO.write(image, "JPG", new File(imagePath));
                        imageType = false;
                    }

                }
                if (!"".equals(images)){
                    OfficeContent content = new OfficeContent();
                    content.setContent(buffer);
                    content.setImages(images);
                    content.setFileName(fileName);
                    content.setRemark(param);
                    String createTime = getCreateTime();
                    content.setCreateTime(createTime);
                    list.add(content);
                }
            }

            boolean add = officeContentService.add(list);
            if (add){
                jsonResult.setData(list);
                jsonResult.setMsg("ok");
                jsonResult.setSuccess(true);
            }else {
                jsonResult.setMsg("error");
                jsonResult.setSuccess(false);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 删除PPT文件
            File pptFile = new File(filePath);
            if (pptFile.exists()) {
                pptFile.delete();
            }
        }
        return jsonResult;
    }*/

    private static String getCreateTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = format.format(new Date());
        return createTime;
    }

    private DateTimeFormatter getFormatter(String s) {
        return DateTimeFormatter.ofPattern(s);
    }

    private static String generateUniqueCode() {
        LocalDate currentDate = LocalDate.now();
        //String dateString = currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String randomString = Long.toString(new Date().getTime());
        //randomString = randomString.substring(randomString.length(), randomString.length());
        //String uniqueCode = dateString + randomString;
        return randomString;
    }

    private BufferedImage compressImage2(BufferedImage image, int targetWidth, int targetHeight, float quality) {
        BufferedImage compressedImage = null;
        try {
            // 创建缩放后的图片
            compressedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = compressedImage.createGraphics();
            graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            graphics2D.drawImage(image, 0, 0, targetWidth, targetHeight, null);
            graphics2D.dispose();

            // 压缩图片质量
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(compressedImage, "jpg", outputStream);

            // 转换为字节数组返回
            return ImageIO.read(new ByteArrayInputStream(outputStream.toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static BufferedImage compressImage3(BufferedImage image, int targetWidth, int targetHeight, float quality) {
        int imageWidth = image.getWidth();
        int imageHeight = image.getHeight();

        // 计算等比例缩放后的宽度和高度
        double scaleFactor = Math.min((double) targetWidth / imageWidth, (double) targetHeight / imageHeight);
        int scaledWidth = (int) (imageWidth * scaleFactor);
        int scaledHeight = (int) (imageHeight * scaleFactor);

        // 创建缩放后的图片
        BufferedImage compressedImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = compressedImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(image, 0, 0, scaledWidth, scaledHeight, null);
        graphics2D.dispose();

        return compressedImage;
    }

    public static BufferedImage compressImage4(BufferedImage image, int targetWidth, int targetHeight, float quality, int maxSizeKB) {
        try {
            // 创建缩放后的图片
            BufferedImage compressedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = compressedImage.createGraphics();
            graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            graphics2D.drawImage(image, 0, 0, targetWidth, targetHeight, null);
            graphics2D.dispose();

            // 压缩图片质量直到大小满足要求
            while (calculateSize(compressedImage) > maxSizeKB * 1024) {
                // 压缩图片质量
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(compressedImage, "jpg", outputStream);

                // 将压缩后的图片数据读入缓冲区
                ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
                compressedImage = ImageIO.read(inputStream);

                // 调整图片质量
                quality -= 0.1; // 减少0.1以减小质量
                if (quality <= 0) {
                    break; // 避免进入死循环
                }
            }

            return compressedImage;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 计算图片大小（单位：字节）
    private static long calculateSize4(BufferedImage image) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            return outputStream.toByteArray().length;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    public static BufferedImage compressImage(BufferedImage image, int targetWidth, int targetHeight, int maxSizeKB) {
        try {
            // 计算等比例缩放后的宽度和高度
            double scaleFactor = Math.min((double) targetWidth / image.getWidth(), (double) targetHeight / image.getHeight());
            int scaledWidth = (int) (image.getWidth() * scaleFactor);
            int scaledHeight = (int) (image.getHeight() * scaleFactor);

            // 创建缩放后的图片
            BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = scaledImage.createGraphics();
            graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            graphics2D.drawImage(image, 0, 0, scaledWidth, scaledHeight, null);
            graphics2D.dispose();

            // 压缩图片质量直到大小满足要求
            int currentSizeKB = (int) (calculateSize(scaledImage) / 1024);
            while (currentSizeKB > maxSizeKB) {
                // 压缩图片质量
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(scaledImage, "png", outputStream);

                // 将压缩后的图片数据读入缓冲区
                ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
                scaledImage = ImageIO.read(inputStream);

                // 重新计算图片大小
                currentSizeKB = (int) (calculateSize(scaledImage) / 1024);

                // 如果质量已经很低，但图片大小仍超过要求，则直接退出循环
                if (currentSizeKB <= maxSizeKB || scaleFactor <= 0.1) {
                    break;
                }

                // 调整图片大小
                scaleFactor -= 0.1;
                scaledWidth = (int) (image.getWidth() * scaleFactor);
                scaledHeight = (int) (image.getHeight() * scaleFactor);
                BufferedImage tempImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
                Graphics2D tempGraphics2D = tempImage.createGraphics();
                tempGraphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                tempGraphics2D.drawImage(image, 0, 0, scaledWidth, scaledHeight, null);
                tempGraphics2D.dispose();
                scaledImage = tempImage;
            }

            return scaledImage;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 计算图片大小（单位：字节）
    private static long calculateSize(BufferedImage image) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            return outputStream.toByteArray().length;
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }


    @RequestMapping("/excelUpload")
    @ResponseBody
    public JsonResult excelUpload(@RequestParam("file") MultipartFile file, @RequestParam("param")String param){
        JsonResult jsonResult = new JsonResult();
        if (file.isEmpty()) {
            jsonResult.setMsg("文件为空");
            jsonResult.setSuccess(false);
            return jsonResult;
        }
        List<OfficeContent> list = new ArrayList<>();
        Workbook workbook = null;
        String originalFilename = file.getOriginalFilename();
        try {
            LocalDate currentDate = LocalDate.now();
            String date_2 = currentDate.format(getFormatter("yyyy-MM-dd"));
            if (file.getOriginalFilename().endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(file.getInputStream());
                extracted1(param, list, workbook, originalFilename, date_2);

            } else if (file.getOriginalFilename().endsWith(".xls")) {
                workbook = new HSSFWorkbook(file.getInputStream());
                extracted2(param, list, workbook, originalFilename, date_2);
            } else {
                jsonResult.setMsg("文件格式不支持");
                jsonResult.setSuccess(false);
                return jsonResult;
            }

            List<OfficeContent> add = officeContentService.add(list);
            if (!add.isEmpty()){
                jsonResult.setData(add);
                jsonResult.setMsg("ok");
                jsonResult.setSuccess(true);
            }else {
                jsonResult.setMsg("error");
                jsonResult.setSuccess(false);
            }
        }catch (Exception e){
            e.printStackTrace();
            jsonResult.setMsg("error");
            jsonResult.setSuccess(false);
        }finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return jsonResult;
    }

    private void extracted2(String param, List<OfficeContent> list, Workbook workbook, String originalFilename, String date_2) throws IOException {
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            if (sheet instanceof HSSFSheet) {
                HSSFSheet hssfSheet = (HSSFSheet) sheet;
                for (HSSFShape shape : hssfSheet.getDrawingPatriarch().getChildren()) {
                    if (shape instanceof HSSFPicture) {
                        //文字 图片
                        String buffer = "";
                        String images ="";
                        String name = "";
                        String dateString = imagePath + date_2 +"/";
                        String dateFile = "/"+ date_2 +"/";
                        Path path = Paths.get(dateString);
                        if (Files.notExists(path)) {
                            Files.createDirectories(path);
                        } else {
                            //System.out.println("文件夹已存在: " + dateString);
                        }

                        HSSFPicture picture = (HSSFPicture) shape;
                        HSSFClientAnchor anchor = (HSSFClientAnchor) picture.getAnchor();
                        int rowIdx = anchor.getRow1();
                        Row row = sheet.getRow(rowIdx);
                        for (Cell cell : row) {
                            if (cell.getCellType() == CellType.STRING) {
                                buffer += cell.getStringCellValue() +"<br>";
                                //System.out.println("文本数据: " + cell.getStringCellValue());
                            } else if (cell.getCellType() == CellType.BLANK) {
                                //System.out.println("空单元格");
                            } else if (cell.getCellType() == CellType.FORMULA) {
                                //System.out.println("公式: " + cell.getCellFormula());
                            }
                        }
                        //获取图片
                        PictureData pictureData = picture.getPictureData();
                        byte[] imageData = pictureData.getData();
                        BufferedImage image = compressImage(ImageIO.read(new ByteArrayInputStream(imageData)), 800, 600, 300);
                        String date_ = generateUniqueCode();
                        String fileName = dateString + date_ + ".jpg";
                        FileOutputStream fos = new FileOutputStream(fileName);
                        ImageIO.write(image, "jpg", fos);
                        images +=  dateFile + date_ + ".jpg;";
                       // System.out.println("图片保存为: " + fileName);
                        if (!"".equals(images)){
                            OfficeContent content = new OfficeContent();
                            content.setContent(buffer);
                            content.setImages(images);
                            content.setFileName(originalFilename);
                            String createTime = getCreateTime();
                            content.setCreateTime(createTime);
                            content.setRemark(param);
                            list.add(content);
                        }
                    }

                }
            }
        }
    }

    private void extracted1(String param, List<OfficeContent> list, Workbook workbook, String originalFilename, String date_2) throws IOException {
        for (Sheet sheet : workbook) {
            for (POIXMLDocumentPart part : ((XSSFSheet) sheet).getRelations()) {
                if (part instanceof XSSFDrawing) {
                    XSSFDrawing drawing = (XSSFDrawing) part;
                    for (XSSFShape shape : drawing.getShapes()) {
                        if (shape instanceof XSSFPicture) {
                            //文字 图片
                            String buffer = "";
                            String images ="";
                            String name = "";


                            String dateString = imagePath + date_2 +"/";
                            String dateFile = "/"+ date_2 +"/";
                            Path path = Paths.get(dateString);
                            if (Files.notExists(path)) {
                                Files.createDirectories(path);
                            } else {
                                System.out.println("文件夹已存在: " + dateString);
                            }

                            //获取文本
                            XSSFPicture picture = (XSSFPicture) shape;
                            Row row1 = sheet.getRow(((XSSFClientAnchor) picture.getAnchor()).getRow1());
                            for (Cell cell : row1) {
                                if (cell.getCellType() == CellType.STRING) {
                                    buffer += cell.getStringCellValue() +"<br>";
                                   // System.out.println("文本数据: " + cell.getStringCellValue());
                                } else if (cell.getCellType() == CellType.BLANK) {
                                    System.out.println("空单元格");
                                } else if (cell.getCellType() == CellType.FORMULA) {
                                    System.out.println("公式: " + cell.getCellFormula());
                                }

                            }
                            //获取图片
                            PictureData pictureData = picture.getPictureData();
                            byte[] imageData = pictureData.getData();
                            BufferedImage image = compressImage(ImageIO.read(new ByteArrayInputStream(imageData)), 800, 600, 200);
                            String date_ = generateUniqueCode();
                            String fileName = dateString + date_ + ".png";
                            FileOutputStream fos = new FileOutputStream(fileName);
                            ImageIO.write(image, "png", fos);
                            images +=  dateFile + date_ + ".png;";
                           // System.out.println("图片保存为: " + fileName);

                            if (!"".equals(images)){
                                OfficeContent content = new OfficeContent();
                                content.setContent(buffer);
                                content.setImages(images);
                                content.setFileName(originalFilename);
                                String createTime = getCreateTime();
                                content.setCreateTime(createTime);
                                content.setRemark(param);
                                list.add(content);
                            }
                        }
                    }
                }
            }
        }
    }


    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("imageService",imageService);
        return "/office/office_index";
    }

    @RequestMapping("/index2")
    public String index2(Model model){
        model.addAttribute("imageService",imageService);
        return "/office/office_index2";
    }


    @RequestMapping("/infoData/{id}")
    @ResponseBody
    public JsonResult infoData(@PathVariable("id") String id){
        JsonResult jsonResult = new JsonResult();
        OfficeContent content = officeContentService.selectById(Long.parseLong(id));
        jsonResult.setSuccess(true);
        jsonResult.setMsg("ok");
        jsonResult.setData(content);
        return jsonResult;
    }


    /**
     * 导出ppt
     * @param param
     * @param response
     */
    @RequestMapping("/ppt/download")
    @ResponseBody
    public void Download(String param,HttpServletResponse response){
        XMLSlideShow ppt = null;
        ServletOutputStream out = null;
        FileInputStream imageStream = null;
        List<OfficeContent> officeContents = new ArrayList<>();
        try {
            //
            ppt = new XMLSlideShow();
            for (OfficeContent officeContent :officeContents){
                //
                XSLFSlide slide = ppt.createSlide();
                XSLFTextBox textBox = slide.createTextBox();
                textBox.setAnchor(new Rectangle2D.Double(50, 400, 600, 130));
                XSLFTextParagraph xslfTextRuns = textBox.addNewTextParagraph();
                XSLFTextRun xslfTextRun = xslfTextRuns.addNewTextRun();
                xslfTextRun.setFontFamily(FONT_FAMILY, FontGroup.EAST_ASIAN);
                String testContent = officeContent.getContent();
                if (officeContent.getProductName() != null && !"".equals(officeContent.getProductName())){
                    testContent = "产品名称："+ officeContent.getProductName() + "\n" + officeContent.getContent();
                }
                xslfTextRun.setText(testContent);
                xslfTextRun.setFontSize(10D);
                imageStream = new FileInputStream(imagePath + officeContent.getImages().split(";")[0]);
                byte[] pictureData = IOUtils.toByteArray(imageStream);
                XSLFPictureData xslfPictureData = ppt.addPicture(pictureData, org.apache.poi.sl.usermodel.PictureData.PictureType.PNG);
                XSLFPictureShape picture = slide.createPicture(xslfPictureData);
                picture.setAnchor(new Rectangle(50, 30, 600, 350));

            }
            // 设置响应头以便浏览器可以下载文件
            response.setContentType(PPTX_CONTENT_TYPE);
            response.setHeader(HEADER_CONTENT_DISPOSITION, HEADER_ATTACHMENT);

            // 将PPT写入响应输出流
            out = response.getOutputStream();
            ppt.write(out);
            out.flush();
            //out.close();
        } catch (Exception e) {
            e.printStackTrace();

        }finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (imageStream != null) {
                    imageStream.close();
                }
                if (ppt != null) {
                    ppt.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }


    }








}
